import { Modal } from '@opentiny/vue';
import axios from 'axios';
import { API_PREFIX } from '@/constant';

type RequestCancelItem = {
  controller: AbortController;
  time: number;
};
const requestCancel = new Map<string, RequestCancelItem[]>();
const instance = axios.create({
  // baseURL: 'http://127.0.0.1:4523/m1/6536593-6239907-default',
  // baseURL: 'http://localhost:8686',
  // baseURL: '/api',
  // timeout: 5000,
  headers: {
    // 'Service-Worker-Allowed': '/',
  }
});

// 清理过期的请求控制器（超过5分钟）
const cleanupOldControllers = () => {
  const now = Date.now();
  requestCancel.forEach((controllers, url) => {
    const activeControllers = controllers.filter(
      ({ time }) => now - time < 60 * 1000 // 5分钟
    );
    if (activeControllers.length > 0) {
      requestCancel.set(url, activeControllers);
    } else {
      requestCancel.delete(url);
    }
  });
};
const checkAndResetCount = (url: string) => {
  return (requestCancel.get(url) || []).length;
};
instance.interceptors.request.use(
  (config) => {
    config.url = API_PREFIX + config.url;
    localStorage.getItem('token') && (config.headers.Authorization = localStorage.getItem('token'));
    // 存储当前请求的控制器
    let key = config.url!;
    if (config.headers.uniqueId) {
      key += config.headers.uniqueId;
    }
    cleanupOldControllers();

    const controller = new AbortController();
    const signal = controller.signal;
    config.signal = signal;
    // 检查请求频率
    const countInfo = checkAndResetCount(key);

    if (countInfo >= 60) {
      controller.abort();
      return Promise.reject({
        message: '请求过于频繁，请稍后再试',
        code: 429,
        config,
      });
    }

    // 取消相同URL的未完成请求
    if (requestCancel.has(key)) {
      requestCancel.get(key)?.forEach((c: RequestCancelItem) => {
        if (c.controller !== controller) c.controller.abort();
      });
    }

    requestCancel.set(key, [
      ...(requestCancel.get(key) || []),
      {
        controller,
        time: Date.now(),
      },
    ]);

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  (response) => {
    const { status } = response;
    // 自带的状态码
    if (status !== 200) {
      return Promise.reject(response);
    }

    const { code } = response.data;
    codeHandle(code);
    // 自定义的状态码
    if (code !== 200) {
      // 错误处理
    }

    return response.data;
  },
  (error) => {
    // console.log(error);
    codeHandle(error.code);
    errorHandle(error);
    return Promise.reject(error);
  }
);

const codeHandle = (code: number | string) => {
  switch (code) {
    case 0:
      // 错误发送到后端记录
      console.error('错误发送到后端记录');
      break;
    case 429:
      // 错误发送到后端记录
      console.error('错误发送到后端记录');
      Modal.message({
        status: 'error',
        message: '请求过于频繁，请稍后再试',
        id: 'xxxx',
      });
      break;
    case 'ERR_NETWORK':
      // 错误发送到后端记录
      Modal.message({
        status: 'error',
        message: '网络错误,请稍后再试',
        id: 'xxxx',
      });
      break;
    default:
      break;
  }
};

const errorHandle = (error: any) => {
  const { status, config } = error;
  if (status === 401) {
    // 401 清除token信息并跳转到登录页面
    Modal.message({
      status: 'error',
      message: '登录已过期，请重新登录',
      id: '401',
    });
    localStorage.clear();
  }

  if (status === 404) {
    // 无此资源
    Modal.message({
      status: 'error',
      message: '无此资源',
      id: '404',
    });
  }

  if (status === 403) {
    // 无权限
    Modal.message({
      status: 'error',
      message: '无此权限',
      id: '403',
    });
  }

  if (status === 500) {
    // 服务器错误
    console.error(config.url, '服务器错误');
  }
};

export default instance;
